

package yf.mall.service.impl;
import com.github.pagehelper.PageHelper;
import com.yf.response.RRException;
import org.springframework.transaction.annotation.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import yf.mall.common.Const;
import yf.mall.dao.*;
import yf.mall.entity.*;
import yf.mall.enums.AccountTypeEnum;
import yf.mall.enums.MaterialStatusEnum;
import yf.mall.service.AccountService;
import yf.mall.service.UserService;
import  yf.mall.vo.down.MaterialDown;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import java.net.URLEncoder;
import yf.mall.vo.down.MaterialDown;
import javax.servlet.http.HttpServletResponse;
import java.util.stream.Collectors;

import yf.mall.vo.MaterialVo;
import yf.mall.service.MaterialService;
import com.yf.service.impl.BaseServiceImpl;

/**
 * 账户记录Service实现类
 *
 * @author hxf
 * @email 505860922@qq.com
 * @date Sat Oct 17 14:55:42 CST 2020
 */
@Service
public class MaterialServiceImpl extends BaseServiceImpl<MaterialEntity> implements MaterialService {

    private MaterialDao dao;


    @Autowired
    public void setDao(MaterialDao dao) {
        this.dao = dao;
        super.setBaseDao(dao);
    }
    @Autowired
    private ShopDao shopDao;
    @Autowired
    private CommentDao commentDao;
    @Autowired
    private UserService userService;
    @Autowired
    private MallGoodsDao mallGoodsDao;
    @Autowired
    private AccountRecordDao accountRecordDao;
    @Autowired
    private AccountService accountService;
    @Autowired
    private ShopParamDao shopParamDao;

    @Override
    public List<MaterialVo> findVo(MaterialVo vo){
        List<MaterialVo> list = dao.findVo(vo);
        if (list.size() > 0){
            for (MaterialVo materialVo : list) {
                //获取所属店铺
                ShopEntity shopEntity = shopDao.get(materialVo.getMaterial().getShopId());
                if (shopEntity != null){
                    materialVo.getMaterial().setShopEntity(shopEntity);
                }
                //获取发布者编号
                UserEntity userEntity = userService.get(materialVo.getMaterial().getUserId());
                if (userEntity != null){
                    materialVo.getMaterial().setUserCode(userEntity.getCode());
                }
            }
        }
        return list;
    }

    @Override
    public MaterialVo getVo(Long id){
        MaterialVo vo = dao.getVo(id);
        ShopEntity shopEntity = shopDao.get(vo.getMaterial().getShopId());
        if (shopEntity != null){
            vo.getMaterial().setShopEntity(shopEntity);
        }
        UserEntity userEntity = userService.get(vo.getMaterial().getUserId());
        if (userEntity != null){
            vo.getMaterial().setUserCode(userEntity.getCode());
        }
        return vo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int saveVo(MaterialVo vo){
        return dao.save(vo.getEntity());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateVo(MaterialVo vo){
        int update = dao.update(vo.getEntity());
        //素材审核通过 赠送用户优惠券
        if (vo.getMaterial().getStatus().equals(MaterialStatusEnum.YES.getIndex())){
            //获取该店铺的奖励优惠券额度
            ShopParamEntity shopParam = shopParamDao.findByShopId(vo.getMaterial().getShopId());
            if (shopParam == null){
                throw new RRException("请先设置该店铺的素材奖励优惠券");
            }
            BigDecimal rewardCoupon = new BigDecimal(0);
            if (shopParam.getCouponReward().compareTo(BigDecimal.ZERO) > 0){
                rewardCoupon = shopParam.getCouponReward();
            }
            //发布人不为空 和不是公司 才奖励优惠券
            if (vo.getMaterial().getUserId() != null && !vo.getMaterial().getUserId().equals(Const.ADMIN_ID)){
                ShopEntity shopEntity = shopDao.get(vo.getMaterial().getShopId());
                Long shopId = Const.ADMIN_ID;
                if (shopEntity != null){
                    shopId = shopEntity.getId();
                }
                //奖励过优惠券则不在奖励  防止恶刷优惠券
                AccountRecordEntity recordEntity = accountRecordDao.findByToUserIdAndTypeAndInfo(vo.getMaterial().getUserId(), AccountTypeEnum.COUPON.getIndex(), "店铺id:" + shopId + ",素材id:" + vo.getMaterial().getId() + ",用户id:" + vo.getMaterial().getUserId());
                if (recordEntity == null && rewardCoupon.compareTo(BigDecimal.ZERO) > 0){
                    String remark = "用户发布爆款素材审核通过赠送优惠券,店铺id:" + shopId + ",素材id:" + vo.getMaterial().getId() + ",用户id:" + vo.getMaterial().getUserId();
                    accountService.transfer(Const.ADMIN_ID, vo.getMaterial().getUserId(), AccountTypeEnum.COUPON.getIndex(), rewardCoupon, remark);
                }
            }
        }
        return update;
    }



    @Override
    public void downLoad(HttpServletResponse response, List<MaterialVo> list) {
        try {
            List<MaterialDown> datas = list.stream().map(item -> new MaterialDown(item)).collect(Collectors.toList());
            response.setContentType("application/vnd.ms-excel" );
            response.setCharacterEncoding("utf-8" );
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("测试", "UTF-8" );
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx" );
            EasyExcel.write(response.getOutputStream(), MaterialDown.class).sheet("模板" ).doWrite(datas);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }




    /**内部方法**/



    /**外部方法实现**/

    @Override
    public List<MaterialEntity> apiFindAll(Long shopId,String goodsName) {
        List<MaterialEntity> list = dao.apiFindAll(shopId,goodsName);
        if (list != null && list.size() > 0){
            for (MaterialEntity materialEntity : list) {
                // 查出对应的店铺
                ShopEntity shopEntity = shopDao.get(materialEntity.getShopId());
                if (shopEntity != null){
                    materialEntity.setShopEntity(shopEntity);
                }
                //是公司
                if (materialEntity.getShopId().equals(Const.ADMIN_ID)){
                    ShopEntity shop = new ShopEntity();
                    shop.setId(Const.ADMIN_ID);
                    shop.setName("社集优选自营店");
                    shop.setAvatar("1603263922406WechatIMG110.png");
                    materialEntity.setShopEntity(shop);
                }
                //找出对应的产品
                MallGoodsEntity goodsEntity = mallGoodsDao.get(materialEntity.getGoodsId());
                materialEntity.setGoodsImg(goodsEntity.getImg());
                materialEntity.setGoodsPrice(goodsEntity.getNowPrice());

                String time = getFriendlyTime(materialEntity.getCreateTime());
                materialEntity.setTime(time);

                PageHelper.startPage(1,5);
                //找出评论信息
                List<CommentEntity> comments = commentDao.findByGoodsId(materialEntity.getGoodsId());
                if (comments != null && comments.size() > 0){
                    materialEntity.setComments(comments);
                }

            }

        }
        return list;
    }

    @Override
    public List<MaterialEntity> findByUserIdOrGoodsName(Long userId,String goodsName) {
        return dao.findByUserIdOrGoodsName(userId,goodsName);
    }

    public String getFriendlyTime(Date d){
        if (d == null) return "";
        long delta = (new Date().getTime()-d.getTime())/1000;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        if(delta<=0)return sdf.format(d);
        if(delta/(60*60*24*365) >= 2) return sdf.format(d);
        if(delta/(60*60*24*365) > 0) return delta/(60*60*24*365) +"年前";
        if(delta/(60*60*24*30) > 0) return delta/(60*60*24*30) +"个月前";
        if(delta/(60*60*24*7) > 0)return delta/(60*60*24*7) +"周前";
        if(delta/(60*60*24) > 0) return delta/(60*60*24) +"天前";
        if(delta/(60*60) > 0)return delta/(60*60) +"小时前";
        if(delta/(60) > 0)return delta/(60) +"分钟前";
        return "刚刚";
    }

}
